package com.tgy.myplus.基础学习.Thread.Synchronized;

import lombok.SneakyThrows;

/**
 * @author 送你一块二向箔
 * @date 2021/11/08 15:38
 */
public class SafeBank {
    public static void main(String[] args) {
        Account1 account = new Account1(1000,"一号钱包");
        Drawing1 drawing = new Drawing1(account,50,20);
        new Thread(new Drawing1(account,50,20),"甲号取钱").start();
        new Thread(new Drawing1(account,60,0),"乙号取钱").start();
    }

}


//账户
class Account1 {
    int money;
    String name;

    public Account1(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行
class Drawing1 implements Runnable{
    Account1 account;//账户
    int drawingMoney;//取钱
    int nowMoney;//手里得钱

    //构造器
    public Drawing1(Account1 account, int drawingMoney, int nowMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.nowMoney = nowMoney;
    }


    @SneakyThrows
    @Override
    /**
     * synchronized 默认锁的是this，要加上监视器才能生效
     * 下面这种直接加synchronized是不行的
     */
    public void run() {

        /**
         * 代码块
         */
        synchronized(account){
            if (account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"余额不足");
                return;
            }
            //模拟延时，放大问题发生得可能性
            Thread.sleep(100);
            account.money -=drawingMoney;
            nowMoney += drawingMoney;
            System.out.println(account.name+"余额为："+account.money);
            System.out.println(Thread.currentThread().getName()+"手里有："+nowMoney);
        }
    }

}
